
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "spindle.h"

spindle_t
spindle_new()
{
  //
  spindle_t spdl = malloc(sizeof(struct spindle_data));
  if (spdl == NULL)
    {
      printf("out of memory!");
      exit(1);
    }

  spdl->origin_of_graph = malloc(SPINDLE_GRAPH_INITIAL_LENGTH);
  if (spdl->origin_of_graph == NULL)
    {
      printf("out of memory!");
      exit(1);
    }
  spdl->length_of_graph = SPINDLE_GRAPH_INITIAL_LENGTH;
  spdl->tail = spdl->origin_of_graph;
  
  memset(spdl->origin_of_graph, 0, spdl->length_of_graph);
  
  return spdl;
}

void
spindle_free(spindle_t spdl)
{
  free(spdl->origin_of_graph);
  free(spdl);
}

size_t
spindle_occur(spindle_t spdl, int* elements, int size)
{
  mrr_byte_t * savedpoint = spdl->tail;
  size_t bound = savedpoint - spdl->origin_of_graph;

  spdl->tail += sizeof(int) * size + 1;

  mrr_byte_t *celltail;
  celltail = spdl->tail;

  // amount of cell elements
  *celltail = size;

  printf("size: %d\n", *(spdl->tail));

  // arrange


  int *q;
  q = elements + (size - 1);
  int i;
  for (i = size; i > 0; i--)
    {
      if (*q > bound)
        {
          printf("out of bound(tail:%d): %d\n", bound, *q);
          spdl->tail = savedpoint;
          break;
        }
      celltail -= sizeof(int);
      *celltail = *q;
      q--;
    }

  return spdl->tail - spdl->origin_of_graph;
}

void
spindle_printbytes(const spindle_t spdl)
{
  mrr_byte_t *p;
  for (p = spdl->origin_of_graph; p <= spdl->tail; p++)
    {
      printf("%2x", *p);
    }
  printf("\n");
}

void
spindle_print(const spindle_t spdl)
{

  mrr_byte_t *celltail = spdl->tail;
  while (celltail > spdl->origin_of_graph)
    {
      int size;
      size = *celltail;

      int i;
      for (i = size; i > 0; i--)
        {
          celltail -= sizeof(int);
          printf("%d ", *((int*) celltail));

        }
      printf("; (%d)]\n", size);
      celltail--;
    }
}